package com.ikunikun.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ikunikun.constant.MessageConstant;
import com.ikunikun.context.BaseContext;
import com.ikunikun.dto.OrdersPaymentDTO;
import com.ikunikun.dto.OrdersSubmitDTO;
import com.ikunikun.entity.*;
import com.ikunikun.exception.AddressBookBusinessException;
import com.ikunikun.exception.OrderBusinessException;
import com.ikunikun.mapper.*;
import com.ikunikun.service.OrderService;
import com.ikunikun.utils.WeChatPayUtil;
import com.ikunikun.vo.OrderPaymentVO;
import com.ikunikun.vo.OrderSubmitVO;
import com.ikunikun.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

	@Resource
	private OrderMapper orderMapper;
	@Resource
	private OrderDetailMapper orderDetailMapper;
	@Resource
	private AddressBookMapper addressBookMapper;
	@Resource
	private ShoppingCartMapper shoppingCartMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private WeChatPayUtil weChatPayUtil;
	@Resource
	private WebSocketServer webSocketServer;

	/**
	 * 提交订单
	 * @param ordersSubmitDTO
	 * @return
	 */
	@Override
	@Transactional
	public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
		// 处理各种业务异常（地址为空，购物车为空）
		AddressBook address = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
		if (Objects.isNull(address)){
			throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
		}

		ShoppingCart cart = new ShoppingCart();
		Long userId = address.getUserId();
		cart.setUserId(userId);
		List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(cart);
		if (Objects.isNull(shoppingCartList) || shoppingCartList.size() == 0){
			throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
		}

		// 向订单表插入1条数据
		Orders orders = new Orders();
		BeanUtils.copyProperties(ordersSubmitDTO, orders);
		orders.setOrderTime(LocalDateTime.now());
		orders.setStatus(Orders.PENDING_PAYMENT);
		orders.setPayStatus(Orders.UN_PAID);
		orders.setNumber(userId.toString() + System.currentTimeMillis());
		orders.setPhone(address.getPhone());
		orders.setConsignee(address.getConsignee());
		orders.setUserId(userId);
		orderMapper.insert(orders);

		// 向订单明细表插入n条数据
		List<OrderDetail> orderDetailList = shoppingCartList.stream().map(shoppingCart -> {
			OrderDetail orderDetail = new OrderDetail();
			BeanUtils.copyProperties(shoppingCart, orderDetail);
			orderDetail.setOrderId(orders.getId());
			return orderDetail;
		}).collect(Collectors.toList());
		orderDetailMapper.insertList(orderDetailList);

		// 清空购物车
		shoppingCartMapper.clean(userId);

		// 封装OrderSubmitVO
		OrderSubmitVO orderSubmitVo = OrderSubmitVO.builder()
				.id(orders.getId())
				.orderTime(orders.getOrderTime())
				.orderNumber(orders.getNumber())
				.orderAmount(orders.getAmount())
				.build();
		return orderSubmitVo;
	}

	/**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), 	//商户订单号
                new BigDecimal(0.01), 			//支付金额，单位 元
                "苍穹外卖订单", 						//商品描述
                user.getOpenid() 					//微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

		// 对商家端进行提示
        orderMapper.update(orders);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("type", 1);
		jsonObject.put("orderId", orders.getId());
		jsonObject.put("content", "订单号: " + outTradeNo);
		String jsonString = JSON.toJSONString(jsonObject);
		webSocketServer.sendToAllClient(jsonString);
    }

	/**
	 * 用户催单
	 * @param id
	 * @return
	 */
	@Override
	public void reminder(Long id) {
		// 根据id查询订单
		Orders order = orderMapper.getById(id);
		if (Objects.isNull(order)){
			throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
		}

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("type", 2);
		jsonObject.put("orderId", id);
		jsonObject.put("content", "订单号: " + order.getNumber());
		String json = jsonObject.toString();

		webSocketServer.sendToAllClient(json);
	}
}
